#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main(void)
{
    char buff[1024];
    int fd1, fd2;
    int ret;

    /* 打开 srcfile 文件 */
    fd1 = open("./src_file", O_RDONLY);
    if (-1 == fd1) {
        printf("Error: open src_file failed!\r\n");
        return -1;
    }
    /* 新建 destfile 文件，并打开 */
    fd2 = open("./dest_file", O_WRONLY | O_CREAT, 
                    S_IRWXU | S_IRGRP | S_IROTH);
    if (-1 == fd2) {
        printf("Error: open dest_file failed!\r\n");
        goto error2;
    }
    /* 将 srcfile 读写位置移动到从头偏移500字节的位置 */
    ret = lseek(fd1, 500, SEEK_SET);
    if (-1 == ret) {
        goto error2;
    }
    /* 读取 srcfile 文件，大小 1KBytes */
    ret = read(fd1, buff, sizeof(buff));
    if (-1 == ret) {
        printf("Error: read src_file failed!\r\n");
        goto error2;
    }
    /* 将 destfile 读写位置定位到文件头 */
    ret = lseek(fd2, 0, SEEK_SET);
    if (-1 == ret) {
        goto error2;
    }
    /* 写入 destfile 文件，大小 1KBytes */
    ret = write(fd2, buff, sizeof(buff));
    if (-1 == ret) {
        printf("Error: write dest_file failed!\r\n");
        goto error2;
    }
    printf("OK: test sucessful!\r\n");
    ret = 0;

error2:
    close(fd2);

error1:
    close(fd1);

    return ret;
}